package com.banciyuan.bcywebview.biz.topic;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.SpecialApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.listview.NoScrollListView;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.biz.share.ShareActivity;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.Recommend;
import de.greenrobot.daoexample.model.Special;
import de.greenrobot.daoexample.model.TopicDetailItem;

/**
 * Created by squall on 2015/8/14.
 */
public class TopicDetailActivity extends BaseActivity implements View.OnClickListener, ActionbarHelper.OnActionCallbacks {

    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;
    private PullToRefreshListView refreshListView;
    private LayoutInflater inflater;
    private NoScrollListView footListView;
    private Boolean hasMore = true;
    private ListView mContentLv;
    private TextView topic_title;
    private TextView topic_subtitle;
    private ImageView topic_cover;
    private LinearLayout topic_label;
    private LinearLayout topic_more_btn;
    private RequestQueue queue;
    private TopicDetailAdapter mAdapter;
    private TopicDetailItem topicDetailItem;
    private List<Special> slist = new ArrayList<>();
    private TopicDetailFootAdapter footAdapter;
    private Intent mIntent;
    protected int special_id;
    private ActionbarHelper mActionbarHelper;
    private View mActionBarView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_topic_show);
        initArgs();
        initActionbar();
        initProgressbar();
        initUi();
        initAction();
        initData();
        getFooterData();
    }

    @Override
    protected void initArgs() {
        inflater = LayoutInflater.from(this);
        queue = VolleyQueue.getRquest(this);
        mIntent = getIntent();
        special_id = mIntent.getIntExtra(gotoUtil.INTENT_VALUE_ONE, 0);
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.topic_detail));
        mActionbarHelper.setActionCallbacks(this);
        mActionbarHelper.addOneAction(R.drawable.share_black);
    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi() {
        refreshListView = (PullToRefreshListView) findViewById(R.id.refresh_lv);
        mContentLv = refreshListView.getRefreshableView();

        View headView = inflater.inflate(R.layout.topic_list_head, null);
        topic_title = (TextView) headView.findViewById(R.id.topic_detail_title);
        topic_subtitle = (TextView) headView.findViewById(R.id.topic_detail_subtitle);
        topic_cover = (ImageView) headView.findViewById(R.id.iv_main);
        topic_label = (LinearLayout) headView.findViewById(R.id.ll_topic_tags);

        View footView = inflater.inflate(R.layout.topic_list_footer, null);
        footListView = (NoScrollListView) footView.findViewById(R.id.topic_footer_list);
        topic_more_btn = (LinearLayout) footView.findViewById(R.id.topic_more_btn);
        footListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                gotoUtil.gotoAct(TopicDetailActivity.this, TopicDetailActivity.class, slist.get(i).getSpecial_id());
            }
        });

        mContentLv.addHeaderView(headView);
        mContentLv.addFooterView(footView);
    }

    @Override
    protected void initData() {

        String url = HttpUtils.BASE_URL + SpecialApi.getDetail();
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.SPECIAL_ID, String.valueOf(special_id)));
        HashMap<String, String> map = HttpUtils.getData(paramsList);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String result) {
                if (StatusCodeUtils.dealStatusCode(result, TopicDetailActivity.this)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        JSONObject jsonObject1 = jsonObject.getJSONObject(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        TopicDetailItem temp = gson.fromJson(jsonObject1.toString(), TopicDetailItem.class);
                        popIllegalData(temp);
                        dealData(temp);
                    } catch (Exception e) {
                        e.printStackTrace();
                        mProgressbarHelper.onFailed();
                        refreshListView.onRefreshComplete();
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
                refreshListView.onRefreshComplete();
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, TopicDetailActivity.this, map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        queue.add(requestParam);

    }

    private void popIllegalData(TopicDetailItem temp) {
        List<Recommend> illegalRecommend = new ArrayList<Recommend>();
        List<Recommend> tempRecommend = temp.getRecommend();
        for (int i = 0; i < tempRecommend.size(); i++) {
            if (-1 != TopicTypeFactory.getTopicType(tempRecommend.get(i).getType(), tempRecommend.get(i).getData().getType())) {
                illegalRecommend.add(tempRecommend.get(i));
            }
        }
        temp.setRecommend(illegalRecommend);
    }

    private void dealData(TopicDetailItem temp) {
        if (null != topicDetailItem) {
            topicDetailItem.getRecommend().clear();
            topicDetailItem.getRecommend().addAll(temp.getRecommend());
        } else {
            topicDetailItem = temp;
        }
        if (null == mAdapter) {
            mAdapter = new TopicDetailAdapter(topicDetailItem, TopicDetailActivity.this);
            refreshListView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
        if (!TextUtils.isEmpty(topicDetailItem.getTitle())) {
            topic_title.setText(Html.fromHtml(topicDetailItem.getTitle()));
        }
        if (!TextUtils.isEmpty(topicDetailItem.getIntro())) {
            topic_subtitle.setText(Html.fromHtml(topicDetailItem.getIntro()));
        }
        ImageLoader.getInstance().displayImage(topicDetailItem.getCover_link(), topic_cover, ImageOptions.options);
        List<String> mainLables = topicDetailItem.getLabels();
        if (null != mainLables && mainLables.size() > 0) {
            topic_label.removeAllViews();
            for (int i = 0; i < mainLables.size(); i++) {
                TextView tv = (TextView) View.inflate(this, R.layout.topic_tag_view, null);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(UIUtils.dip2px(50, this), UIUtils.dip2px(20, this));
                params.setMargins(0, UIUtils.dip2px(-2, this), UIUtils.dip2px(16, this), 0);
                tv.setLayoutParams(params);
                tv.setText(mainLables.get(i));
                topic_label.addView(tv);
            }
        }
        mProgressbarHelper.onSuccess();
        refreshListView.onRefreshComplete();
    }

    @Override
    protected void initAction() {

        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                initData();

            }
        });

        topic_more_btn.setOnClickListener(this);
    }

    private void getFooterData() {
        String url = HttpUtils.BASE_URL + SpecialApi.getRecommend();
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.SPECIAL_ID, String.valueOf(special_id)));
        HashMap<String, String> map = HttpUtils.getData(paramsList);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String result) {
                if (StatusCodeUtils.dealStatusCode(result, TopicDetailActivity.this)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        JSONArray data = jsonObject.getJSONArray("data");
                        Gson gson = new Gson();
                        List<Special> temp = gson.fromJson(data.toString(), new TypeToken<List<Special>>() {
                        }.getType());
                        dealFooterJson(temp);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, TopicDetailActivity.this, map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        queue.add(requestParam);
    }

    private void dealFooterJson(List<Special> temp) {
        slist.clear();
        slist.addAll(temp);
        if (null != footAdapter) {
            footAdapter.notifyDataSetChanged();
        } else {
            footAdapter = new TopicDetailFootAdapter(slist, TopicDetailActivity.this);
            footListView.setAdapter(footAdapter);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.topic_more_btn:
                gotoUtil.gotoAct(this, TopicDetailListActivity.class, 69);
                break;
            case R.id.iv_more:
                goShare();
                break;
        }
    }

    private void goShare() {
        String url = "http://bcy.net/special/detail/" + special_id;
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("content", String.format(getString(R.string.share_topic), topicDetailItem.getTitle(), url));
        map.put("title", topicDetailItem.getTitle());
        map.put("url", url);
        map.put("imagePath", topicDetailItem.getCover_link());
        Intent intent = new Intent();
        intent.setClass(this, ShareActivity.class);
        intent.putExtra("showWarnBtn", false);
        intent.putExtra("map", map);
        startActivity(intent);
        overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }

    @Override
    public void onBackClick() {
        finish();
    }

    @Override
    public void onActionClick(int id) {
        switch (id) {
            case R.id.base_action_bar_itemone:
                goShare();
                break;
        }
    }

}
